package com.bocloud.cmp.driver.providers.impl;

import java.util.Date;

import org.springframework.stereotype.Service;

import com.bocloud.cmp.driver.config.Configuration;
import com.bocloud.cmp.driver.providers.AuthDriver;
import com.bocloud.cmp.driver.providers.ali.AliAuthDriver;
import com.bocloud.cmp.driver.providers.intf.AuthProvider;
import com.bocloud.cmp.driver.providers.jd.JdAuthDriver;
import com.bocloud.cmp.driver.providers.os.OSAuthDriver;
import com.bocloud.cmp.driver.providers.os.OSDriver.Version;
import com.bocloud.cmp.driver.providers.vmware.VmwareAuthDriver;
import com.bocloud.cmp.driver.utils.VendorConverter;
import com.bocloud.cmp.enums.VendorType;
import com.bocloud.cmp.model.Butler;
import com.bocloud.common.model.BsmResult;

/**
 * 验证服务接口实现类
 * 
 * @author weiwei
 *
 */
@Service("authProvider")
public class AuthProviderImpl implements AuthProvider {

	@Override
	public BsmResult auth(String vendor, String region) {
		BsmResult result = null;
		AuthDriver driver = null;
		Long start = new Date().getTime();
		Butler butler = null;
		// 处理缓存写入慢的问题
		while (true) {
			butler = Configuration.instance().getConfig(vendor);
			if (null != butler) {
				break;
			}
			Long time = new Date().getTime() - start;
			if (time > 10 * 1000) {
				return new BsmResult(false, "认证超时！");
			}
		}
		VendorType type = VendorConverter.convert(butler.getCategory());
		switch (type) {
		case JDYUN:
			driver = new JdAuthDriver(butler.getAccessKey(), butler.getSecretKey(), butler.getUrl(), region);
			result = driver.auth();
			break;
		case ALIYUN:
			driver = new AliAuthDriver(butler.getAccessKey(), butler.getSecretKey(), region);
			result = driver.auth();
			break;
		case OPENSTACK:
			driver = new OSAuthDriver(butler.getUrl(), butler.getUsername(), butler.getPassword(), butler.getTenant(),
					butler.getDomainName(), butler.getProjectName(), Version.valueOf(butler.getVersion()));
			result = driver.auth();
			break;
		case VMWARE:
			driver = new VmwareAuthDriver(butler.getUrl(), butler.getUsername(), butler.getPassword());
			result = driver.auth();
			if (result.isSuccess()) {
				String version = butler.getVersion();
				if (!result.getData().toString().contains(version)) {
					result = new BsmResult(false, "版本信息不对应");
				}
			}
			break;
		default:
			result = new BsmResult(false, "NOT_SUPPORTED");
			break;
		}
		return result;
	}

}
